import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import Feature from 'ol/Feature'
import {Circle, LineString, Point, Polygon} from 'ol/geom'
import {boundingExtent, getCenter} from 'ol/extent'

/* 封装的矢量图层FeatureLayer
  opt : {
    style ,//ol.style.Style
    map, //ol.map
    features,//ol.collection
   其余参数参考ol.layer.Vector 对象的构造参数opt_options
  }
*/
class TyFeatureLayer {
  constructor(opt) {
    this.map = opt.map
    this.vectorLayerSource = new VectorSource({wrapX: false, features: opt.features})
    this.vectorLayer = new VectorLayer({
      source: this.vectorLayerSource,
      style: opt.style
    })
    this.vectorLayer.setZIndex(this.map.getLayers().getLength() + 1)
    this.map.addLayer(this.vectorLayer)
  }
  // 添加Feature
  addFeature(feature) {
    this.vectorLayerSource.addFeature(feature)
    return feature
  }
  addFeatures(feature) {
    this.vectorLayerSource.addFeatures(feature)
    return feature
  }
  // 插入一个Geomtry
  addGeomertry(geom, style, id, properties) {
    const feature = new Feature({
      geometry: geom
    })
    if (id) {
      feature.setId(id)
    }
    if (properties) {
      feature.setProperties(properties, false)
    }
    if (style) {
      feature.setStyle(style)
    }
    return this.addFeature(feature)
  }
  // 插入一个点；
  addPoint(point, style, id, properties) {
    const geom = new Point(point)
    return this.addGeomertry(geom, style, id, properties)
  }
  // 插入一条线；
  addLineString(coordinates, style, id, properties) {
    const geom = new LineString(coordinates)
    return this.addGeomertry(geom, style, id, properties)
  }
  // 插入一个面；
  addPolygon(coordinates, style, id, properties) {
    const geom = new Polygon(coordinates)
    return this.addGeomertry(geom, style, id, properties)
  }
  // 插入一个圆；
  addCircle(centerPoint, radius, style, id, properties) {
    const geom = new Circle(centerPoint, radius)
    return this.addGeomertry(geom, style, id, properties)
  }
  // 删除指定的feature
  removeFeature(feature) {
    this.vectorLayerSource.removeFeature(feature)
  }
  // 清除此图层中的所有feature
  clear() {
    this.vectorLayerSource.clear()
  }
  // 获取图层中心点
  getFeatureCenter(feature) {
    if (feature) {
      const extent = boundingExtent(feature.getGeometry().getCoordinates()[0][0])
      const center = getCenter(extent)
      return center
    }
    return null
  }
  // 通过指定ID查找对应的feature对象
  getFeatureById(id) {
    return this.vectorLayerSource.getFeatureById(id)
  }
  // 获取所有的ol.feature对象
  getFeatures() {
    return this.vectorLayerSource.getFeatures()
  }
  getVectorLayer() {
    return this.vectorLayer
  }
  // 解除矢量地层与地图的关联
  dispose() {
    this.map.removeLayer(this.vectorLayer)
  }
}

export default TyFeatureLayer
